#!/usr/bin/env python
# coding=utf-8

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

import logging,logging.config
from vavava import util
from tracker.tracker_dispatcher import TrackerDispatcher

__author__ = 'vavava'

def usage():
    print ( """tracker [-d debug_level][-t timeout][-ids id[|id]]""")

def main():
    import time
    from sys import argv
    from tracker.config_file import GripperConfig
    config=GripperConfig()

    argv_dic=util.parse_argvs(argv)
    if argv_dic and argv_dic.get('-config'):
        config.load(argv_dic.get('-config'))
    else:
        config.load('tracker.conf')

    logging.config.fileConfig(config.log_config_file)
    log=logging.getLogger(config.logger)

    if argv_dic:
        if argv_dic.get('-d'):    config.debug_level=int(argv_dic.get('-d'))
        if argv_dic.get('-t'):    config.sock_timeout=float(argv_dic.get('-t'))
        if argv_dic.get('-ids'):  config.userTokens=argv_dic.get('-ids').split('|')

    display_str="""Tracking Begin[%s]: User tokens=%s Debug level=%d Socket timeout=%f """
    log.info(display_str%(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())),
                          config.userTokens,config.debug_level,config.sock_timeout))

    tracer=TrackerDispatcher(
        debug_level=config.debug_level,
        period=config.period,
        soc_timeout=config.sock_timeout,
        log=log,
        userTokens=config.userTokens,
        host=config.host,
        port=config.port,
        user=config.user,
        passwd=config.passwd,
        db=config.db
    )
    tracer.start()
    if tracer.TimerIsRunning:
        log.info('gripper:started')
    else:
        log.error('gripper:failed on start gripper')

    try:
        while True:
            #print('running')
            time.sleep(1)
    except(KeyboardInterrupt):
        log.info('hello DB  user canceled!!')
    tracer.stop()
    log.info('gripper:stopped')

    log.info("""Tracking ended at %s"""%
             time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))

if __name__ == '__main__':
    main()
